package db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BankDatabase {
	private DbConnector db;

	public BankDatabase() {
		this.db = DbConnector.getInstance();
	}

	private Customer getCustomer(int loginId, int password) {
		String query = "SELECT * FROM Customers WHERE LoginId = '" + loginId + "' AND Password = '" + password+ "'";
		Customer c = null;
		ResultSet rs;
		try {
			rs = db.doQuery(query);
			while (rs.next()) {
				c = new Customer(rs.getInt(1), rs.getInt(2), rs.getInt(3),
						rs.getString(4), rs.getString(5));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return c;
	}
	
	public ArrayList<Account> getAccounts(int loginId) {
		String query = "SELECT * FROM Accounts WHERE LoginId = '" + loginId + "'";
		
		ArrayList<Account> accounts = new ArrayList();
		
		ResultSet rs;
		try {
			rs = db.doQuery(query);
			while (rs.next()) {
				Account account = new Account(rs.getInt(1), rs.getString(2), rs.getDouble(3));
				accounts.add(account);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return accounts;
	}
	
	
	public void WithdrawalCash(String accountNumber,int amount) {
		String query = "UPDATE accounts SET accounts.Balance = (accounts.Balance - '" + amount + "') WHERE " +
				"(accounts.AccountNumber = '" + accountNumber + "') AND (accounts.Balance -'" + amount + "') >= 0";
		
		try{
		 db.doUpdate(query);
		  
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void DepositCash(String accountNumber,int amount) {
		String query = "UPDATE accounts SET accounts.Balance = (accounts.Balance + '" + amount + "') WHERE " +
				"(accounts.AccountNumber = '" + accountNumber + "') AND (accounts.Balance -'" + amount + "') >= 0";
		
		try{
		 db.doUpdate(query);
		  
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public boolean authenticateUser(int userLoginId, int userPassword) {
		Customer userCustomer = getCustomer(userLoginId,userPassword);

		if (userCustomer != null)
			return true;
		else
			return false;
	}
}
